package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //先给检查组添加信息
        checkGroupDao.add(checkGroup);
        //再添加检查组和检查项得关联关系
        //得到刚刚添加检查组的ID
        method(checkGroup, checkitemIds);
    }

    @Override
    public PageResult find(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页
        PageHelper.startPage(currentPage, pageSize);
        Page<CheckGroup> checkGroups = checkGroupDao.selectByCondition(queryString);
        //得到总条数
        long total = checkGroups.getTotal();
        //得到数据
        List<CheckGroup> result = checkGroups.getResult();
        return new PageResult(total, result);
    }

    @Override
    public void delete(Integer id) {
        //先删除关联表的数据
        checkGroupDao.deleteByAndId(id);
        checkGroupDao.delete(id);
    }

    @Override
    public List<Integer> findItemByGroupId(Integer id) {
        return checkGroupDao.findItemByGroupId(id);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //先修改检查组的基本信息
        checkGroupDao.update(checkGroup);
        //删除检查组和检查项的关联关系
        checkGroupDao.deleteByAndId(checkGroup.getId());
        //添加新的关联关系
        method(checkGroup, checkitemIds);
    }

    public void method(CheckGroup checkGroup, Integer[] checkitemIds) {
        Integer checkGroupId = checkGroup.getId();
        if (checkitemIds.length > 0 && checkitemIds != null) {
            for (Integer checkItemId : checkitemIds) {
                HashMap<String, Integer> map = new HashMap<>();
                //封装成map集合
                map.put("checkGroupId", checkGroupId);
                map.put("checkItemId", checkItemId);
                //调用方法
                checkGroupDao.addCheckGroupAndCheckItem(map);
            }
        }
    }
}
